<template>
  <div class="message-template">
    <!-- 搜索和操作栏 -->
    <div class="operation-bar">
      <div class="left">
        <el-input
          v-model="searchQuery"
          placeholder="搜索模板名称"
          clearable
          @clear="handleSearch"
          @keyup.enter="handleSearch"
          style="width: 200px"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-select
          v-model="categoryFilter"
          placeholder="选择分类"
          clearable
          @change="handleSearch"
          style="width: 150px; margin-left: 16px"
        >
          <el-option
            v-for="item in categories"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </div>
      <div class="right">
        <el-button type="primary" @click="handleCreate">
          <el-icon><Plus /></el-icon>新建模板
        </el-button>
        <el-button @click="handleManageCategory">
          <el-icon><Folder /></el-icon>分类管理
        </el-button>
        <el-button @click="handleImport">
          <el-icon><Upload /></el-icon>导入
        </el-button>
        <el-button @click="handleExport">
          <el-icon><Download /></el-icon>导出
        </el-button>
      </div>
    </div>

    <!-- 模板列表 -->
    <el-card class="template-list">
      <el-table
        :data="templateList"
        border
        v-loading="loading"
        style="width: 100%"
      >
        <el-table-column prop="name" label="模板名称" min-width="150" />
        <el-table-column prop="category" label="分类" width="120">
          <template #default="scope">
            <el-tag>{{ scope.row.categoryName }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="消息类型" width="120">
          <template #default="scope">
            <el-tag :type="getMessageTypeTag(scope.row.type)">
              {{ getMessageTypeLabel(scope.row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="variables" label="变量" min-width="200">
          <template #default="scope">
            <el-tag
              v-for="variable in scope.row.variables"
              :key="variable"
              class="variable-tag"
              size="small"
            >
              {{ variable }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="更新时间" width="180" />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="scope">
            <el-button
              type="primary"
              link
              @click="handleEdit(scope.row)"
            >编辑</el-button>
            <el-button
              type="primary"
              link
              @click="handlePreview(scope.row)"
            >预览</el-button>
            <el-button
              type="primary"
              link
              @click="handleCopy(scope.row)"
            >复制</el-button>
            <el-button
              type="danger"
              link
              @click="handleDelete(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pageNum"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 模板表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'create' ? '新建模板' : '编辑模板'"
      width="800px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="模板名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入模板名称" />
        </el-form-item>
        <el-form-item label="分类" prop="categoryId">
          <el-select v-model="form.categoryId" placeholder="请选择分类">
            <el-option
              v-for="item in categories"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="消息类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择消息类型">
            <el-option
              v-for="type in messageTypes"
              :key="type.value"
              :label="type.label"
              :value="type.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="模板内容" prop="content">
          <el-input
            v-model="form.content"
            type="textarea"
            :rows="6"
            placeholder="请输入模板内容，使用 {{变量名}} 表示变量"
          />
        </el-form-item>
        <el-form-item label="变量列表">
          <div class="variables-list">
            <div
              v-for="(variable, index) in form.variables"
              :key="index"
              class="variable-item"
            >
              <el-input
                v-model="variable.name"
                placeholder="变量名"
                style="width: 150px"
              />
              <el-input
                v-model="variable.description"
                placeholder="变量描述"
                style="width: 200px"
              />
              <el-select
                v-model="variable.type"
                placeholder="变量类型"
                style="width: 120px"
              >
                <el-option label="文本" value="text" />
                <el-option label="数字" value="number" />
                <el-option label="日期" value="date" />
                <el-option label="时间" value="datetime" />
                <el-option label="选项" value="select" />
              </el-select>
              <el-input
                v-if="variable.type === 'select'"
                v-model="variable.options"
                placeholder="选项值，用逗号分隔"
                style="width: 200px"
              />
              <el-button
                type="danger"
                link
                @click="removeVariable(index)"
              >
                <el-icon><Delete /></el-icon>
              </el-button>
            </div>
            <el-button type="primary" link @click="addVariable">
              <el-icon><Plus /></el-icon>添加变量
            </el-button>
          </div>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm" :loading="submitting">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 预览对话框 -->
    <el-dialog
      v-model="previewVisible"
      title="模板预览"
      width="600px"
    >
      <div class="preview-content">
        <div class="preview-header">
          <h3>{{ previewData.name }}</h3>
          <el-tag>{{ previewData.categoryName }}</el-tag>
          <el-tag :type="getMessageTypeTag(previewData.type)">
            {{ getMessageTypeLabel(previewData.type) }}
          </el-tag>
        </div>
        <div class="preview-body">
          <div class="preview-variables">
            <div
              v-for="variable in previewData.variables"
              :key="variable.name"
              class="preview-variable"
            >
              <span class="label">{{ variable.description || variable.name }}：</span>
              <el-input
                v-if="variable.type === 'text'"
                v-model="previewValues[variable.name]"
                placeholder="请输入预览值"
              />
              <el-input-number
                v-else-if="variable.type === 'number'"
                v-model="previewValues[variable.name]"
                placeholder="请输入预览值"
              />
              <el-date-picker
                v-else-if="variable.type === 'date'"
                v-model="previewValues[variable.name]"
                type="date"
                placeholder="选择日期"
              />
              <el-date-picker
                v-else-if="variable.type === 'datetime'"
                v-model="previewValues[variable.name]"
                type="datetime"
                placeholder="选择日期时间"
              />
              <el-select
                v-else-if="variable.type === 'select'"
                v-model="previewValues[variable.name]"
                placeholder="请选择"
              >
                <el-option
                  v-for="option in variable.options.split(',')"
                  :key="option"
                  :label="option"
                  :value="option"
                />
              </el-select>
            </div>
          </div>
          <div class="preview-result">
            <div class="result-title">预览结果：</div>
            <div class="result-content" v-html="previewResult"></div>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 分类管理对话框 -->
    <el-dialog
      v-model="categoryDialogVisible"
      title="分类管理"
      width="500px"
    >
      <div class="category-list">
        <div
          v-for="(category, index) in categories"
          :key="category.id"
          class="category-item"
        >
          <el-input
            v-model="category.name"
            placeholder="分类名称"
            style="width: 200px"
          />
          <el-input-number
            v-model="category.sort"
            :min="0"
            :max="999"
            placeholder="排序"
            style="width: 100px"
          />
          <el-switch
            v-model="category.visible"
            active-text="显示"
            inactive-text="隐藏"
          />
          <el-button
            type="danger"
            link
            @click="removeCategory(index)"
          >
            <el-icon><Delete /></el-icon>
          </el-button>
        </div>
        <el-button type="primary" link @click="addCategory">
          <el-icon><Plus /></el-icon>添加分类
        </el-button>
      </div>
      <template #footer>
        <el-button @click="categoryDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveCategories" :loading="submitting">
          保存
        </el-button>
      </template>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog
      v-model="importDialogVisible"
      title="导入模板"
      width="400px"
    >
      <el-upload
        class="template-upload"
        drag
        action="/api/message/template/import"
        :headers="uploadHeaders"
        :on-success="handleUploadSuccess"
        :on-error="handleUploadError"
        :before-upload="beforeUpload"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          将文件拖到此处，或<em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            支持 .xlsx, .xls 格式文件，文件大小不超过 10MB
          </div>
        </template>
      </el-upload>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Search,
  Plus,
  Delete,
  Folder,
  Upload,
  Download,
  UploadFilled
} from '@element-plus/icons-vue'
import {
  getMessageTemplateList,
  createMessageTemplate,
  updateMessageTemplate,
  deleteMessageTemplate,
  getMessageCategoryList,
  createMessageCategory,
  updateMessageCategory,
  deleteMessageCategory,
  sortMessageCategories,
  updateCategoryVisibility,
  getMessageTypes
} from '@/api/message'

// 搜索和筛选
const searchQuery = ref('')
const categoryFilter = ref('')

// 数据加载状态
const loading = ref(false)
const submitting = ref(false)

// 分页数据
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 列表数据
const templateList = ref([])
const categories = ref([])

// 对话框显示状态
const dialogVisible = ref(false)
const previewVisible = ref(false)
const categoryDialogVisible = ref(false)
const importDialogVisible = ref(false)
const dialogType = ref('create')

// 表单引用
const formRef = ref(null)

// 表单数据
const form = reactive({
  id: '',
  name: '',
  categoryId: '',
  type: '',
  content: '',
  variables: [],
  remark: ''
})

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入模板名称', trigger: 'blur' }],
  categoryId: [{ required: true, message: '请选择分类', trigger: 'change' }],
  type: [{ required: true, message: '请选择消息类型', trigger: 'change' }],
  content: [{ required: true, message: '请输入模板内容', trigger: 'blur' }]
}

// 消息类型
const messageTypes = ref([])

// 预览数据
const previewData = ref({})
const previewValues = ref({})

// 上传相关
const uploadHeaders = {
  Authorization: `Bearer ${localStorage.getItem('token')}`
}

// 初始化数据
onMounted(async () => {
  await Promise.all([
    fetchTemplateList(),
    fetchCategories(),
    fetchMessageTypes()
  ])
})

// 获取模板列表
const fetchTemplateList = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      query: searchQuery.value,
      categoryId: categoryFilter.value
    }
    const res = await getMessageTemplateList(params)
    templateList.value = res.data.list
    total.value = res.data.total
  } catch (error) {
    console.error('获取模板列表失败:', error)
    ElMessage.error('获取模板列表失败')
  } finally {
    loading.value = false
  }
}

// 获取分类列表
const fetchCategories = async () => {
  try {
    const res = await getMessageCategoryList()
    categories.value = res.data
  } catch (error) {
    console.error('获取分类列表失败:', error)
    ElMessage.error('获取分类列表失败')
  }
}

// 获取消息类型
const fetchMessageTypes = async () => {
  try {
    const res = await getMessageTypes()
    messageTypes.value = res.data
  } catch (error) {
    console.error('获取消息类型失败:', error)
    ElMessage.error('获取消息类型失败')
  }
}

// 处理搜索
const handleSearch = () => {
  pageNum.value = 1
  fetchTemplateList()
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchTemplateList()
}

const handleCurrentChange = (val) => {
  pageNum.value = val
  fetchTemplateList()
}

// 新建模板
const handleCreate = () => {
  dialogType.value = 'create'
  Object.assign(form, {
    id: '',
    name: '',
    categoryId: '',
    type: '',
    content: '',
    variables: [],
    remark: ''
  })
  dialogVisible.value = true
}

// 编辑模板
const handleEdit = (row) => {
  dialogType.value = 'edit'
  Object.assign(form, row)
  dialogVisible.value = true
}

// 预览模板
const handlePreview = (row) => {
  previewData.value = row
  previewValues.value = {}
  previewVisible.value = true
}

// 复制模板
const handleCopy = async (row) => {
  try {
    const newTemplate = { ...row }
    delete newTemplate.id
    newTemplate.name = `${row.name} - 副本`
    await createMessageTemplate(newTemplate)
    ElMessage.success('复制成功')
    fetchTemplateList()
  } catch (error) {
    console.error('复制失败:', error)
    ElMessage.error('复制失败')
  }
}

// 删除模板
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该模板吗？', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      await deleteMessageTemplate(row.id)
      ElMessage.success('删除成功')
      fetchTemplateList()
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  })
}

// 管理分类
const handleManageCategory = () => {
  categoryDialogVisible.value = true
}

// 添加分类
const addCategory = () => {
  categories.value.push({
    id: Date.now(),
    name: '',
    sort: categories.value.length,
    visible: true
  })
}

// 移除分类
const removeCategory = (index) => {
  categories.value.splice(index, 1)
}

// 保存分类
const saveCategories = async () => {
  submitting.value = true
  try {
    const promises = categories.value.map(async (category) => {
      if (category.id > 1000) {
        // 新分类
        await createMessageCategory(category)
      } else {
        // 更新分类
        await updateMessageCategory(category)
        await updateCategoryVisibility(category.id, category.visible)
      }
    })
    await Promise.all(promises)
    await sortMessageCategories(categories.value.map(c => c.id))
    ElMessage.success('保存成功')
    categoryDialogVisible.value = false
    fetchCategories()
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败')
  } finally {
    submitting.value = false
  }
}

// 导入模板
const handleImport = () => {
  importDialogVisible.value = true
}

// 导出模板
const handleExport = async () => {
  try {
    const res = await fetch('/api/message/template/export', {
      headers: {
        Authorization: `Bearer ${localStorage.getItem('token')}`
      }
    })
    const blob = await res.blob()
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `消息模板_${new Date().toLocaleDateString()}.xlsx`
    link.click()
    window.URL.revokeObjectURL(url)
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  }
}

// 上传相关处理
const beforeUpload = (file) => {
  const isExcel = /\.(xlsx|xls)$/.test(file.name)
  const isLt10M = file.size / 1024 / 1024 < 10

  if (!isExcel) {
    ElMessage.error('只能上传 Excel 文件!')
    return false
  }
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过 10MB!')
    return false
  }
  return true
}

const handleUploadSuccess = (response) => {
  ElMessage.success('导入成功')
  importDialogVisible.value = false
  fetchTemplateList()
}

const handleUploadError = () => {
  ElMessage.error('导入失败')
}

// 变量相关处理
const addVariable = () => {
  form.variables.push({
    name: '',
    description: '',
    type: 'text',
    options: ''
  })
}

const removeVariable = (index) => {
  form.variables.splice(index, 1)
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitting.value = true
    
    if (dialogType.value === 'create') {
      await createMessageTemplate(form)
      ElMessage.success('创建成功')
    } else {
      await updateMessageTemplate(form)
      ElMessage.success('更新成功')
    }
    
    dialogVisible.value = false
    fetchTemplateList()
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error(error.message || '提交失败')
  } finally {
    submitting.value = false
  }
}

// 预览结果计算
const previewResult = computed(() => {
  if (!previewData.value.content) return ''
  
  let result = previewData.value.content
  Object.entries(previewValues.value).forEach(([key, value]) => {
    const regex = new RegExp(`{{${key}}}`, 'g')
    result = result.replace(regex, value || `{{${key}}}`)
  })
  return result
})

// 工具函数
const getMessageTypeTag = (type) => {
  const typeMap = {
    system: 'info',
    notification: 'success',
    warning: 'warning',
    error: 'danger'
  }
  return typeMap[type] || ''
}

const getMessageTypeLabel = (type) => {
  const typeItem = messageTypes.value.find(t => t.value === type)
  return typeItem ? typeItem.label : type
}
</script>

<style lang="scss" scoped>
.message-template {
  padding: 20px;

  .operation-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    .left {
      display: flex;
      gap: 16px;
    }

    .right {
      display: flex;
      gap: 16px;
    }
  }

  .template-list {
    .variable-tag {
      margin-right: 8px;
      margin-bottom: 4px;
    }

    .pagination-container {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }

  .variables-list {
    .variable-item {
      display: flex;
      gap: 8px;
      margin-bottom: 8px;
      align-items: center;
    }
  }

  .preview-content {
    .preview-header {
      display: flex;
      align-items: center;
      gap: 16px;
      margin-bottom: 20px;

      h3 {
        margin: 0;
      }
    }

    .preview-body {
      .preview-variables {
        margin-bottom: 20px;

        .preview-variable {
          display: flex;
          align-items: center;
          margin-bottom: 16px;

          .label {
            width: 120px;
            text-align: right;
            margin-right: 16px;
          }
        }
      }

      .preview-result {
        padding: 16px;
        background-color: #f5f7fa;
        border-radius: 4px;

        .result-title {
          font-weight: bold;
          margin-bottom: 8px;
        }

        .result-content {
          white-space: pre-wrap;
          word-break: break-all;
        }
      }
    }
  }

  .category-list {
    .category-item {
      display: flex;
      align-items: center;
      gap: 16px;
      margin-bottom: 16px;
    }
  }

  .template-upload {
    :deep(.el-upload-dragger) {
      width: 100%;
    }
  }
}
</style> 